﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class Car : MonoBehaviour {

    public Transform[] Way;
    private int index = 0;
    public float speed=3;
    public float hp=400;
    public int value = 150;
    private float Hp;
    private Animator carBoom;
    private TurretBuild tB;
    public GameObject gainMoney;
    
    private void Start()
    {
        Way = RoadPoint.Positions;
        Hp = hp;
        carBoom = transform.GetComponent<Animator>();
    }

    private void Update()
    {
        Move();
    }

    private void Move()
    {
        if (index > Way.Length - 1) return;
        //旋转战车方向
       
        Vector3 direction = Way[index].position - transform.position;
        direction.z = 0f;
        direction = direction.normalized;
        
        float angle = Vector3.Angle(transform.up, direction);
        // Debug.Log("angle" + angle);
        transform.Rotate(transform.forward, angle);
        //transform.DOLocalRotate(new Vector3(0,0,angle), 0.5f);
        Vector3 moveDirection = transform.up;
        transform.position += moveDirection * Time.deltaTime * speed;
       
        if (Vector2.Distance(Way[index].position,transform.position)<0.2f)
        {
            index++;
        }
        if(index>Way.Length-1)
        {
            ReachEnd();
        }
    }
    private void ReachEnd()
    {
        GameObject.Destroy(this.gameObject);
    }
    private void OnDestroy()
    {
        CarProduction.carAliveCount--;
    }


    public void TakeDamage(float damage)
    {
        if (hp <= 0) return;
        hp -= damage;
        Debug.Log("hp" + hp);
        if(hp<=0)
        {
            carBoom.SetTrigger("Boom");
            Invoke("Die", 1);
        }
    }

    private void Die()
    {
        tB = GameObject.Find("GameManager").GetComponent<TurretBuild>();
        
        tB.ShowGainMoney(value,transform.position);
        tB.ChangeMoney(-value);
        GameObject.Destroy(this.gameObject);

    }
}
